import json
from http.server import HTTPServer,BaseHTTPRequestHandler
from game.rom import ROM
from urllib import parse
from io import BytesIO

class RomHttpServer(HTTPServer):
    def setRom(self,romdir):
        self.rom = ROM(romdir)
    def getRom(self):
        return self.rom
    
    def run(port, romdir):
        try:
            server = RomHttpServer(('0.0.0.0', port), RomResquest)
            server.setRom(romdir)
            server.serve_forever()
        except Exception:
            server.socket.close
            server.server_close
            
class RomResquest(BaseHTTPRequestHandler):
    PARAM_ID = "ID"
    PARAM_ADDR = "ADDRESS"
    PARAM_LENGTH = "LENGTH"
    
    def log_message(self, format: str, *args):
        return
    
    def do_GET(self):
        data = None
        contentType = "application/json"
        res = parse.urlparse(self.path).query
        if(self.path.startswith("/list")):
            data = self.server.getRom().getNames()
        elif(self.path.startswith("/info")):
            for param in res.split("&"):
                p = param.split("=")
                if(p[0].upper() == RomResquest.PARAM_ID):data = self.server.getRom().getInfo(int(p[1]))
        elif(self.path.startswith("/data")):
            rid = 0
            address = 0
            length = 0
            contentType = "application/octet-stream"
            for param in res.split("&"):
                p = param.split("=")
                if(p[0].upper() == RomResquest.PARAM_ID):rid = int(p[1])
                if(p[0].upper() == RomResquest.PARAM_ADDR):address = int(p[1])
                if(p[0].upper() == RomResquest.PARAM_LENGTH):length = int(p[1])
            data = BytesIO(self.server.getRom().getData(rid, address, length))
        self.send_response(200)
        self.send_header("Content-type",contentType)
        self.end_headers()
        if(contentType.endswith("json")):self.wfile.write(json.dumps(data).encode())
        if(contentType.endswith("octet-stream")):self.wfile.write(data.getvalue())

   